import { ref, reactive, SetupContext, computed, onMounted, watch, nextTick, toRefs } from 'vue';
import storage from '@/lib/storage/storage';
import utils from '@/lib/utils';
import { useStore } from "vuex";
import { useRoute, useRouter } from "vue-router";
function setup(props: any, ctx: SetupContext): any {
    const store = useStore();
    const { UIAuth, bodySize } = toRefs(store.state);
    const saveUIAuth = (data: any) => store.commit("saveUIAuth", data);
    const updateUserInfo = (data: any) => store.commit("updateUserInfo", data);
    const updateMenuList = (data: any) => store.commit("updateMenuList", data);
    let menuList = reactive<any[]>([]); // 菜单列表
    const config = window.CONFIG;
    const activeMenu = ref("/index"); // 当前访问的路由
    const activeRouteName = ref("Index"); // 当前访问的路由名称
    const historyList = reactive<any[]>([]);
    const historyLeft = ref(0);
    const historyWidth = ref(0);
    const historyDefaultWidth = ref(150); // 历史记录列表宽度多出的数据
    const noKeepAlive = reactive<string[]>([]); // 要缓存的路由页面
    const isCollapse = ref(false);
    const HomeWinStartShow = ref(false);
    const route = useRoute();
    const router = useRouter();
    const homeHistory = ref<any>();
    const homeHistoryList = ref<any>();
    // 监听路由变化
    watch(() => route.path, () => {
        activeMenu.value = route.path;
        let isKeepAlive = false;
        if ((!utils.empty(route.meta) && route.meta.keepAlive)) {
            isKeepAlive = true;
        }
        SetHistoryMenu(route.path, route.name as string, isKeepAlive);
    });
    const MenuActive = (path: string) => {
        SetActiveMenuToPage(path);
    };
    // 向历史记录中加入菜单
    const SetHistoryMenu = (path: string, routeName: string, isKeepAlive: boolean) => {
        let index: number = -1;
        let routerExist: boolean = false;
        historyList.forEach((item: any, key: number) => {
            if (item.route === path) {
                index = key;
                item.active = true;
                routerExist = true;
            } else {
                item.active = false;
            }
        });
        if (index < 0) {
            const menu: any = getMenuTitle(path);
            if (!utils.empty(menu.id)) {
                routerExist = true;
                const history: any = {
                    id: menu.id,
                    title: menu.title,
                    route: menu.route,
                    routerName: routeName,
                    icon: menu.icon,
                    icon_color: menu.icon_color,
                    img: menu.img,
                    active: true,
                    index: 0,
                };
                historyList.push(history);
                index = historyList.length - 1;
            }
        }
        if (routerExist) {
            CalcHistoryLeft(index);
        }
        if (isKeepAlive) {
            index = noKeepAlive.findIndex((val: string) => val === routeName);
            if (index < 0) {
                noKeepAlive.push(routeName);
            }
        }
    };

    // 删除历史菜单 项
    const DelHistoryMenu = (index: number) => {
        const delRouter = historyList[index];
        const active: boolean = delRouter.active;
        if (historyList.length > 1) {
            historyList.splice(index, 1);
        }
        let activeIndex = -1;
        if (active) {
            activeIndex = historyList.length - 1;
            historyList[activeIndex].active = true;
            activeMenu.value = historyList[activeIndex].route;
            activeRouteName.value = historyList[activeIndex].routerName;
            router.push({ path: historyList[activeIndex].route });
        } else {
            let temKey: number = 0;
            for (const item of historyList) {
                if (item.active) {
                    activeIndex = temKey;
                    break;
                }
                temKey++;
            }
        }
        const key = noKeepAlive.findIndex((item: any) => item === delRouter.routerName);
        if (key >= 0) {
            noKeepAlive.splice(key, 1);
        }
        CalcHistoryLeft(activeIndex);
    };

    // 历史记录列表向左移动
    const historyLeftMove = () => {
        // 获取历史记录DIV
        const historyDiv = homeHistory.value;
        const divWidth = historyDiv.clientWidth;
        const listWidth = historyWidth.value - historyDefaultWidth.value;
        let listLeft = historyLeft.value;
        const maxLeft = 0;
        let minLeft = divWidth - listWidth;
        if (minLeft > 0) {
            minLeft = 0;
        }
        if ((divWidth - listWidth + historyLeft.value) < 0) {
            listLeft -= historyDiv.clientWidth;
        }
        if (listLeft > maxLeft) {
            listLeft = 0;
        }
        if (listLeft < minLeft) {
            listLeft = minLeft;
        }
        historyLeft.value = listLeft;
    };
    // 历史记录列表向右移动
    const historyRightMove = () => {
        // 获取历史记录DIV
        const historyDiv = homeHistory.value as Element;
        const divWidth = historyDiv.clientWidth - historyDefaultWidth.value;
        const listWidth = historyWidth.value;
        let listLeft = historyLeft.value;
        const maxLeft = 0;
        let minLeft = divWidth - listWidth;
        if (minLeft > 0) {
            minLeft = 0;
        }
        if ((divWidth - listWidth + historyLeft.value) < 0) {
            listLeft += historyDiv.clientWidth;
        }
        if (listLeft > maxLeft) {
            listLeft = 0;
        }
        if (listLeft < minLeft) {
            listLeft = minLeft;
        }
        historyLeft.value = listLeft;
    };

    // 计算历史菜单 左边距的距离
    const CalcHistoryLeft = (index: number) => {
        nextTick(() => {
            // 获取历史记录DIV
            const historyDiv = homeHistory.value;
            const historyListDiv = homeHistoryList.value;
            if (!historyDiv || !historyListDiv) {
                return false;
            }
            // 当前激活的历史记录左边距离 = 左边距离+自身的宽度
            let itemDivLeft: number = 0;
            // 历史记录DIV 的宽度
            let historyItemWidth: number = historyDefaultWidth.value;
            const divChildren: HTMLDivElement[] = historyListDiv.$el.children;
            let key = 0;
            for (const item of divChildren) {
                historyItemWidth += item.clientWidth + 4;
                if (key === index) {
                    itemDivLeft = historyItemWidth - historyDefaultWidth.value;
                }
                key++;
            }
            historyWidth.value = historyItemWidth;
            const divWidth = historyDiv.clientWidth;
            const listWidth = historyItemWidth - historyDefaultWidth.value;
            let minLeft = divWidth - listWidth;
            if (minLeft > 0) {
                minLeft = 0;
            }
            let temHistoryLeft = divWidth - itemDivLeft;
            if (temHistoryLeft > 0) {
                temHistoryLeft = 0;
            }
            if (temHistoryLeft < minLeft) {
                temHistoryLeft = minLeft;
            }
            historyLeft.value = temHistoryLeft;
        });
    };
    // 查询菜单
    const getMenuTitle = (path: string): any => {
        let menu: any = {};
        for (const item of menuList) {
            if (item.route === path) {
                menu = item;
                break;
            }
        }
        return menu;
    };
    // 设置当前激活菜单 并 跳转到知道页面 应在字类 中调用
    const SetActiveMenuToPage = (path: string): void => {
        activeMenu.value = path;
        router.push({ path });
        // this.SetHistoryMenu(route);
    };
    // 移除index.html页面的loading
    function moveIndexPageLoading() {
        document.getElementById("app-loading")?.remove();
        document.getElementById("app-loading-css")?.remove();
    }
    // 初始化函数  应在字类 created() 函数中调用
    function Init() {
        menuList = storage.menuList.Get();
        const userInfo = storage.user.Get();
        const uiAuth = storage.uiAuth.Get();
        // 更菜单信息
        updateMenuList(menuList);
        // 更用户信息
        updateUserInfo(userInfo);
        // 更新UI权限
        saveUIAuth(uiAuth);
        // 跳转到首页路由
        activeMenu.value = route.path;
        activeRouteName.value = route.name as string;
        if (utils.empty(activeMenu.value) || activeMenu.value === "/") {
            activeMenu.value = "/index";
        }
        router.push({ path: activeMenu.value });
        let isKeepAlive = false;
        if ((!utils.empty(route.meta) && route.meta.keepAlive)) {
            isKeepAlive = true;
        }
        SetHistoryMenu(activeMenu.value, activeRouteName.value, isKeepAlive);
    }
    onMounted(() => {
        moveIndexPageLoading();
    });
    Init();
    return {
        UIAuth,
        bodySize,
        menuList,
        config,
        activeMenu,
        activeRouteName,
        historyList,
        historyLeft,
        historyWidth,
        historyDefaultWidth,
        getKeepAlive: computed(() => noKeepAlive),
        isCollapse,
        MenuActive,
        HomeWinStartShow,
        homeHistory,
        homeHistoryList,
        DelHistoryMenu,
        historyLeftMove,
        historyRightMove
    };
}
export default setup;
